import hmr from './hmr'
import m from './m'
import $const from './const'
import md5 from 'md5'
import api from './api'
const keys = $const.messageKey
const tokenKey = $const.tokenKey
const configKey = $const.configKey

// 加载热加载
hmr()

// axios init

m.cmd('register', async p=>{
    let {
        email,
        password,
    } = p.data || {}

    return api.user.register({
        email,
        password,
    })
})
m.cmd('login', p=>{
    console.log(p.data)
    let {
        email,
        password
    } = p.data || {}

    return api.user.login({
        email,
        password
    }).then(res=>{
        let { token } = res || {}
        localStorage.setItem(tokenKey, token || '')
    })
})
m.cmd('translate', p=>{
    let {
        to,
        q
    } = p.data || {}

    return api.user.trans({
        to,
        q
    })
})
m.cmd('isLogin', p=>{
    return !!localStorage.getItem(tokenKey)
})
m.cmd('logout', p=>{
    localStorage.removeItem(tokenKey)
})

function setConfig(config){
    localStorage.setItem(configKey, JSON.stringify(config))
}
function getConfig(){
    let config = localStorage.getItem(configKey)
    try{
        config = config? JSON.parse(config):{}
    }catch(err){
        console.warn('error parse config: ', config)
        config = {}
    }
    config.langs = config.langs || $const.defaultLangs
    return config
}

m.cmd('setLangs', p=>{
    let langs = p.data || $const.defaultLangs
    setConfig({
        ...getConfig(),
        langs
    })
})
m.cmd('getLangs', p=>{
    return getConfig().langs
})


// const baiduApi = "https://fanyi-api.baidu.com/api/trans/vip/translate"
// m.cmd('translate', async p=>{
//     if(p.cmd === 'translate'){
//         let q = p.data
//         let from = "auto"
//         let to = "en"
//         let appid = "20211121001005533"
//         let pin = "h60ftDgQf2zknUP1YS27"
//         let salt = new Date().getTime() + ""
//         let sign = md5(appid + q + salt + pin, 32)
//         // console.log("发送请求", `${baiduApi}?q=${q}&from=${from}&to=${to}&appid=${appid}&salt=${salt}&sign=${sign}`)
//         return axios.get(`${baiduApi}?q=${q}&from=${from}&to=${to}&appid=${appid}&salt=${salt}&sign=${sign}`).then(res=>{
//             return res.data?.trans_result?.map?.(r=>r.dst)?.join(',')
//         })
//     }
// })
// 翻译接口
// let q = val
//         let from = "auto"
//         let to = "en"
//         let appid = "20211121001005533"
//         let pin = "h60ftDgQf2zknUP1YS27"
//         let salt = new Date().getTime() + ""
//         let sign = md5(appid + q + salt + pin, 32)
//         console.log("发送请求", `${baiduApi}?q=${q}&from=${from}&to=${to}&appid=${appid}&salt=${salt}&sign=${sign}`)
//         axios.get(`${baiduApi}?q=${q}&from=${from}&to=${to}&appid=${appid}&salt=${salt}&sign=${sign}`).then(res=>{
//             console.log(res.data)
//         })